package cn.edu.gsau.info.controller;



import cn.edu.gsau.info.models.*;
import cn.edu.gsau.info.service.IUserRoleService;
import cn.edu.gsau.info.service.IUserService;
import cn.edu.gsau.info.service.IUserTypeService;
import cn.edu.gsau.info.service.impl.UserServiceImpl;
import cn.edu.gsau.info.service.impl.UserTypeServiceImpl;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.sun.org.apache.xml.internal.security.utils.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")


public class UserController {


    @Autowired
    private DefaultKaptcha producer;

    @Value("${gsau.upload.path}")
    private String path;


    @Autowired
    IUserService userService;
    @Autowired
    IUserRoleService userRoleService;
    @Autowired
    IUserTypeService userTypeService;

    @Autowired
    RedisTemplate redisTemplate;
    private LoginUser loginUser;

    @PostMapping("/login")
    public  ResponseResult login(@RequestBody User user,
                                 @RequestHeader("captchaToken") String captchaToken){
        System.out.println(user);
        String text1 =(String) redisTemplate.opsForValue().get(captchaToken);
        if(user.getCaptcha().equals(text1)){
            return userService.login(user);
        }else{
            return new ResponseResult(Code.BUSINESS_EXCEPTION, "验证码错误,请重新输入");
        }
    }


    @ResponseBody
    @PostMapping("/captcha")
    public Object captcha()throws IOException {
//1:获取验证码
        String text = producer.createText();
        System.out.println("登录验证码："+text);
//2:将验证生成base64图片
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        BufferedImage image = producer.createImage(text);
        ImageIO.write(image, "png", out);
        String base64bytes = Base64.encode(out.toByteArray());
        String src = "data:image/png;base64," + base64bytes;
//3：验证码保存到redis中
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token,text,5, TimeUnit.MINUTES);
//4:向前端响应验证码
        Map<String, Object> map = new HashMap<>(2);
        map.put("captchaToken", token);
        map.put("img", src);
        return map;
    }

    @PostMapping("/logout")
    public ResponseResult logout(){
        return userService.logout();
    }



    @PostMapping("/getmenuanduser")
    public ResponseResult getMenuAndUser(){
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return userService.getMenuAndUser(loginUser);
    }
    @Transactional
    @PostMapping ("/insert")
    public ResponseResult insert(@RequestBody BigUser bigUser) {
        try {
            System.out.println(bigUser);
            userService.insert(bigUser);
            userRoleService.insert(bigUser);
            return new ResponseResult(200,"添加用户成功",bigUser.getUser().getId());
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseResult(401,"添加用户失败");
        }
    }

    @PostMapping ("/userType")
    public ResponseResult userType() {
        try {
            User user=new User();


            List list=userTypeService.list();
            System.out.println(list);
            return new ResponseResult(200,"添加用户成功",list);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseResult(401,"添加用户失败");
        }
    }
}
